package org.jiamandan.com.config;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.jiamandan.com.constant.BizConstant;

import java.net.InetSocketAddress;
import java.nio.ByteOrder;

/**
 * @version Revision 1.0.1
 * @版权：版权所有 (c) 2021
 * @see:
 * @创建日期：2023-03-16 14:12
 * @功能说明：
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2023-03-16 14:12	         Lee        	创建
 * @end
 */
public class NettyChannelInitializer extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
        if (socketAddress.getPort() != 18083) {
            channel.pipeline().addLast(new NettyDecoder(ByteOrder.LITTLE_ENDIAN, 1024, 1, 3, 2, 1, 2, 0, 0, true));
//        channel.pipeline().addLast(new NettyYDDecoder(ByteOrder.LITTLE_ENDIAN, 1024, 1,  1, 2,  0, true));
            channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
            /**
             * 处理TCP请求
             */
            // ChannelOutboundHandler，依照逆序执行
            channel.pipeline().addLast("encoder", new ByteArrayEncoder());
            // 属于ChannelInboundHandler，依照顺序执行
            channel.pipeline().addLast("decoder", new ByteArrayDecoder());
        } else {
            ByteBuf delimiter = Unpooled.copiedBuffer("\r\n".getBytes());
            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, delimiter));
            channel.pipeline().addLast(new StringDecoder());
            channel.pipeline().addLast(new StringEncoder());
        }

        // 自定义TCP请求的处理器
        channel.pipeline().addLast(new TcpInboundAdapter());
    }
}
